package org.penguin.study.bk.role.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.penguin.study.bk.base.query.QueryGenerator;
import org.penguin.study.bk.base.vo.Result;
import org.penguin.study.bk.role.entity.Role;
import org.penguin.study.bk.role.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author chengyinghua
 */
@Slf4j
@Tag(name = "角色控制器", description = "角色信息")
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * @return
     * @功能：新增
     */
    @Operation(summary = "角色表-新增组织", description = "组织表-角色组织")
    @PostMapping(value = "/add")
    public Result<Role> add(@RequestBody Role role) {
        Result<Role> result = new Result<>();
        try {
            role.setCreatedBy("admin");
            role.setCreatedTime(LocalDateTime.now());
            roleService.save(role);
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * @return
     * @功能：新增
     */
    @Operation(summary = "组织表-新增组织", description = "组织表-新增组织")
    @PutMapping(value = "/update")
    public Result<Role> update(@RequestBody Role role) {
        Result<Role> result = new Result<>();
        try {
            role.setUpdatedBy("admin");
            role.setUpdatedTime(LocalDateTime.now());
            roleService.updateById(role);
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @GetMapping(value = "/list")
    public Result<?> queryPageList(Role role,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize",
            defaultValue = "10") Integer pageSize, HttpServletRequest request) {

        QueryWrapper<Role> queryWrapper = QueryGenerator.initQueryWrapper(role, request.getParameterMap());
        Page<Role> page = new Page<>(pageNo, pageSize);
        IPage<Role> pageList = roleService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

}
